/**
  * @desc to convert error object to Response Error object
*/

const ResponseError = require('./ResponseError')
const logger = require('../helper/logger')

module.exports = (error) => {
  process.env.NODE_ENV === 'development' && logger.error(error)
  // Handle s3 client error
  if (error.code === 'LIMIT_FILE_SIZE') {
    const responseError = new ResponseError.ValidationError()
    responseError.message = 'The file size exceeds upload limit.'
    return responseError
  }
  // Handle JWT error
  if (error.name === 'TokenExpiredError') {
    return new ResponseError.ExpiredToken()
  } else if (error.name === 'JsonWebTokenError') {
    return new ResponseError.InvalidToken()
  }
  // Handle SQL error
  // NOTE: SQLState values from
  // https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-error-sqlstates.html
  if (error.sqlState && error.sqlState.length) {
    // remove SQLSTATE marker (#) and pad/truncate SQLSTATE to 5 chars
    const sqlState = (`00000${error.sqlState.replace('#', '')}`).slice(-5)
    const sqlStateCode = sqlState.slice(0, 2)
    switch (sqlStateCode) {
      case '02':
        return new ResponseError.NotFound()
      case '28':
        return new ResponseError.InvalidPermission()
      case '08':
      case '0A':
      case '0K':
        return new ResponseError.InvalidQuery()
      case '20':
      case '21':
      case '22':
      case '23':
        return new ResponseError.DuplicatedRecord()
      case '24':
      case '25':
      case '40':
      case '42':
      case '70':
        return new ResponseError.InvalidQuery()
      default:
        return new ResponseError.DatabaseError()
    }
  }
  if (error.id && error.message && error.code) {
    return error
  }
  return new ResponseError.InternalServerError()
}
